package com.ordos.recruit.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author fw
 * @version 1.0
 * @date 2020/6/23 15:57
 */
public class HttpUtils {

    static final Logger log= LoggerFactory.getLogger(HttpUtils.class);
    static OkHttpClient client;
    static{
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5,TimeUnit.SECONDS);
        //builder.connectionPool(new ConnectionPool(5,1,TimeUnit.MINUTES));
        client = builder.build();
    }


    public static JSONObject requestPost(String url,String jsonStr) throws IOException {
        System.out.println("url:"+url);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonStr);
        Request cookieRequest = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response execute = null;
        try {
            execute = client.newCall(cookieRequest).execute();
            return JSONObject.parseObject(execute.body().string());
        } catch (Exception e) {
            log.error("请求地址："+url+",请求参数："+jsonStr+"错误信息："+e.getMessage());
            e.printStackTrace();
        }finally {
            execute.close();
        }
        return null;
    }
}
